package com.example.myapplication.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.airbnb.lottie.animation.content.Content;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

//Text to Speech
public class TTSHelper {

    private TextToSpeech tts;
    private boolean isReady = false;
    private static TTSHelper instance;
    private Activity mActivity;
    private HashMap<String, String > param  = new HashMap<String, String>();

    private TTSHelper(Activity a) {
        mActivity = a;
        tts = new TextToSpeech(a, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status == TextToSpeech.SUCCESS) {
                    tts.setSpeechRate(1.0f);
                    tts.setLanguage(Locale.ENGLISH);
                    isReady = true;
                } else {
                    isReady = false;
                }
            }
        });

        tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String s) {

            }

            @Override
            public void onDone(String s) {
                //TODO 通知UI线程 朗读完毕
                EventBus.getDefault().post( new Object() );
            }

            @Override
            public void onError(String s) {

            }
        });
    }

    public static TTSHelper getInstance(Activity a) {
        if(instance == null) {
            instance = new TTSHelper(a);
        }
        return instance;
    }


    public void speak(String what) {
        if(isReady) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                tts.speak(what, TextToSpeech.QUEUE_FLUSH, new Bundle(), "");
            } else {
                tts.speak(what, TextToSpeech.QUEUE_FLUSH, param);
            }
        }
    }

    public void toFile(String what) {
        if(isReady) {
            String path = mActivity.getExternalFilesDir("").getAbsolutePath();
            path += "/voice.wav";
            tts.speak("", TextToSpeech.QUEUE_FLUSH, param);
            int res = tts.synthesizeToFile(what, param, path);
//            int res = tts.synthesizeToFile(what,new Bundle(), f, "");
            Log.d("TTS", res + "");

        }
    }

    public void stop() {
        if(isReady) {
            tts.stop();
        }
    }

    public void setSpeed(float speed) {
        if(isReady) {
            tts.setSpeechRate(speed);
        }
    }
}
